/*
* @Author: Administrator
* @Date:   2018-01-02 16:26:34
* @Last Modified by:   'baijiwei'
* @Last Modified time: 2018-01-02 16:39:21
*/
const Helmet = require('react-helmet').default

const serializeJs = require('serialize-javascript')
const ejs = require('ejs');
// 解决react异步问题
const ReeactDomServer =require("react-dom/server")
const asyncBootstrap  = require('react-async-bootstrapper').default

const serverRender = (bundleModule, template, req, res) => {
  return new Promise((resolve, reject) => {
    const userAgent = req.headers['user-agent'];
    let bundle
    if (userAgent.indexOf('Windows NT') !== -1 || userAgent.indexOf('Intel Mac') !== -1) {
      bundle = bundleModule.default;
    } else {
      bundle = bundleModule.MobileApp;
    }
    const createStore = bundleModule.createStore;
    const createUserStore = bundleModule.createUserStore
    const stores = createStore()
    const userStore = createUserStore(req.session.user)
    let context = {};
    const app = bundle(stores, userStore, context, req.url);
    asyncBootstrap(app).then(() => {
      const content = ReeactDomServer.renderToString(app);
      const helmet = Helmet.rewind()
      const html = ejs.render(template, {
        content: content,
        newsList: serializeJs(stores),
        userInfo: serializeJs(req.session.user),
        title: helmet.title.toString()
      })
      if(context.url) {
        res.status(302).setHeader('Location',context.url);
        res.end();
        return
      }
      res.send(html);
      resolve()
    }).catch(reject)
  })
}
module.exports = serverRender
